package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/sys_role")
public class SysRoleController {
    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;

    @Autowired
    private ISysMenuService iSysMenuService;


    /**
     * 角色列表分页
     *
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/list")
    private ResultData list(int page, int limit, String name) {
        //设置分页构造器
        Page pageInfo = new Page(page, limit);
        //构造条件构造器
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), SysRole::getName, name);
        lqw.orderByDesc(SysRole::getCreateDate);
        lqw.orderByDesc(SysRole::getUpdateDate);

        iSysRoleService.page(pageInfo, lqw);
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", (int) pageInfo.getTotal());
        map.put("totalPages", (int) (pageInfo.getTotal() / pageInfo.getSize() + 1));
        map.put("pageSize", (int) pageInfo.getSize());
        map.put("currentPage", (int) pageInfo.getCurrent());
        map.put("data", pageInfo.getRecords());
        return ResultData.ok("", map);
    }


    /**
     * 修改角色信息
     *
     * @param roleDto
     * @return
     */
    @PostMapping("/update")
    private ResultData update(@RequestBody RoleDto roleDto) {
        if (roleDto.getMenuids() == null) {
            return ResultData.error("修改数据失败");
        }
        iSysRoleService.roleWithMenu(roleDto);
        return ResultData.ok("修改成功", "");
    }

    /**
     * 修改回显
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {

        //获取管理员信息
        SysRole sysRole = iSysRoleService.getById(id);
        RoleDto roleDto = new RoleDto();
        BeanUtils.copyProperties(sysRole, roleDto);
        //获取对应的菜单表
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, id);
        List<SysRoleMenu> list = iSysRoleMenuService.list(queryWrapper);
        //获取菜单对应编号的IDS
        List<Integer> ids = list.stream().map(item -> {
            String menuId = item.getMenuId();
            return Integer.parseInt(menuId);
        }).collect(Collectors.toList());
//        //获取一级菜单
//        LambdaQueryWrapper<SysMenu> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(SysMenu::getPid, 0);
//        queryWrapper1.in(SysMenu::getId, ids);
//        List<SysMenu> list1 = iSysMenuService.list(queryWrapper1);
        MenuDto menuDto = new MenuDto();
        menuDto.setId(0);
        //传入角色id=0,菜单id作为条件,通过递归的方式找出菜单
        List<MenuDto> collect = iSysMenuService.selectAll(menuDto, ids);
//        //遍历一级菜单,获取一级菜单下面的二级菜单
//        List<MenuDto> collect = list1.stream().map(oneMenu -> {
//            MenuDto menuDto = new MenuDto();
//            BeanUtils.copyProperties(oneMenu, menuDto);
//            //找出二级菜单
//            LambdaQueryWrapper<SysMenu> queryWrapper2 = new LambdaQueryWrapper<>();
//            queryWrapper2.eq(SysMenu::getPid, oneMenu.getId());
//            queryWrapper2.in(SysMenu::getId, ids);
//            List<SysMenu> list2 = iSysMenuService.list(queryWrapper2);
//            //遍历2级菜单,复制菜单到dto中,二级菜单中包含三级菜单
//            List<MenuDto> list4 = list2.stream().map(twoMenu -> {
//                MenuDto menuDtoTwo = new MenuDto();
//                BeanUtils.copyProperties(twoMenu, menuDtoTwo);
//                LambdaQueryWrapper<SysMenu> queryWrapper3 = new LambdaQueryWrapper<>();
//                queryWrapper3.eq(SysMenu::getPid, twoMenu.getId());
//                queryWrapper3.in(SysMenu::getId, ids);
//                List<SysMenu> list3 = iSysMenuService.list(queryWrapper3);
//                menuDtoTwo.setChildren(list3);
//                return menuDtoTwo;
//            }).collect(Collectors.toList());
//
//            menuDto.setChildren(list4);
//            return menuDto;
//        }).collect(Collectors.toList());


        roleDto.setAuthList(collect);

        return ResultData.ok("", roleDto);

    }

    /**
     * 角色列表-全部
     *
     * @return
     */
    @GetMapping("/allData")
    public ResultData allData() {
        List<SysRole> list = iSysRoleService.list();
        return ResultData.ok("", list);
    }

    /**
     * 添加角色
     * @param roleDto
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody RoleDto roleDto){

        if (roleDto.getMenuids() == null) {
            return ResultData.error("添加数据失败");
        }
        iSysRoleService.save(roleDto);
        ArrayList<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Integer id : roleDto.getMenuids()) {
            SysRoleMenu sysRoleMenu=new SysRoleMenu();
            sysRoleMenu.setRoleId(roleDto.getId());
            sysRoleMenu.setMenuId(id.toString());
        }
        iSysRoleMenuService.saveBatch(sysRoleMenus);
        return ResultData.ok("添加成功", "");
    }

    @GetMapping("/del")
    public ResultData delete(String id){
        //从角色表中删除
        iSysRoleService.removeById(id);
        //根据角色id构造条件
        LambdaQueryWrapper<SysRoleMenu> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SysRoleMenu::getRoleId,id);
        //从角色菜单表中删除
        iSysRoleMenuService.remove(lqw);
        return ResultData.ok("删除成功","");
    }

}
